from flask_sqlalchemy import SQLAlchemy
from packages.core.db.decorators import Transactional
from packages.core.auth.login_user_holder import LoginUserHolder
from modules.sys.models.dept import Dept
from packages.tools.base_tool import build_tree, generate_id
from packages.tools.db_tool import DbTool
from sqlalchemy import asc

from modules.sys.validators.dept_validator import DeptForm
from packages.common.base import IdForm, IdsForm


class DeptService():
    """
    部门模块业务处理类
    """
    def __init__(self, db: SQLAlchemy):
        self.model = Dept
        self.db = db

    def detail(self, form: IdForm):
        """
        通过id获取信息
        :param form:
        :return:
        """
        model = self.db.session.query(self.model).get(form.id.data)
        return model

    @Transactional()
    def save(self, form: DeptForm):
        """
        添加部门
        :param form:
        :return:
        """
        model = self.model(**form.data)
        DbTool.check_unique(Dept, "code", model.code, None, "唯一编码已存在！")
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()
        self.db.session.add(model)

    @Transactional()
    def update(self, form: DeptForm):
        """
        修改部门
        :param form:
        :return:
        """
        model = self.model(**form.data)
        DbTool.check_unique(Dept, "code", model.code, model.id, "唯一编码已存在！")
        model.updateUser = LoginUserHolder.get_user_id()

        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )

    @Transactional()
    def remove(self, form: IdsForm):
        """
        删除
        :param form:
        :return:
        """
        self.model().remove(self.model, form.ids.data)

    def list(self):
        """
        部门列表
        """
        list = DbTool.filter_by_custom(Dept).order_by(asc(Dept.sort)).all()
        return Dept.to_dict_list(list)

    def tree(self):
        """
        部门树
        """
        list = DbTool.filter_by_custom(Dept).order_by(asc(Dept.sort)).all()
        return build_tree(Dept.to_dict_list(list))
